<?php
include('controller/poi.inc.php');
class user extends poi
{
   public function title()
{
	return 'User';
}
   function showList()
   {
      global $database;
      $name =  $_GET['name'];
      $idListy = $_GET['id'];

      $select = "SELECT count(ID) as replay FROM lists WHERE ID = '$idListy' AND name = '$name' AND ID_USER = ".$_SESSION['ID'];
      $database->query($select);
      $r=$database->getResult();
      if($r['replay'] == 0)
      {
         echo 'Nie posiadasz listy o nazwie ' .$name ;
         return;
      }
      else
      {
         $select2 = $sql = "SELECT points.id, points.name, points.desc , points.lat, points.lon ,
   cat.name AS cname FROM ((points LEFT JOIN cat ON points.id_cat = cat.id ) LEFT JOIN ucat ON
cat.id_ucat = ucat.id ) LEFT JOIN `list-poi` on points.id = `list-poi`.ID_POINT
WHERE `list-poi`.ID_LIST = ".$idListy;

               $database->query($select2);
         if (mysql_num_rows($database->result) >0)
         {//są jakies punkty na liscie
            echo ' Punkty na liście ' .$name .': <br> ';
            echo' <table border="1" cellpadding="0" cellspacing="0" width="449"   >
   <tr class="b">
      <td width= "10" > &#160; </td>
      <td width= "60" > lon  </td>
      <td width= "60" > lat </td>
      <td width= "90" > name </td>
      <td width= "95" > opis</td>
      <td width= "75" > kategoria</td>
   </tr>';
               
              // $r2=$database->getResult();
               while ($r2=mysql_fetch_array($database->result))
               {
                  echo '<tr> <td  ><input type="checkbox" name="checkbox[]" id="'.$r2['id'].'" value="'.$r2['id'].'" /></td>
                    <td  >'.$r2['lon'].'</td> <td  >'.$r2['lat'].'</td> <td  >'. $r2['name'].'</td>
                  <td width= "80" >'. $r2['desc'].'</td>
                  <td  >'. $r2['cname']. '</td>';
                  echo '</tr>';
               }
    
            echo '</table>';
         }
         else
         {
            echo ' Brak punktów na liście ' .$name .'.<br>';
         }
      }
   }
   function delPointsFromList($checked,$list_id )
   {
      global $database;

      if (empty($checked))
      {//nie zaznaczono zadnego checkboxa
         echo '<br>Aby usunąć punkty zaznacz pole obok wybranych punktów<br>';
         return;
      }
      else
      {
         $where = array();
         foreach($checked as $val)  //dla kazdego zaznaczonego punktu
         {
            //usuwanie z obecnej listy.
            $where[] =  "ID_POINT = ".(int)$val;
         }
         if ( !empty($where) )
         {
            $delete .= "DELETE FROM `list-poi` WHERE ID_LIST =".$list_id." AND (" . implode(' OR ', $where).")";
            $database->query($delete);
            echo '<br>Usunięto zaznaczone punkty z dotychczasowej listy.';
         }
      }
   }
   
   function addToListFromExisting()
{
   $nowaNazwa = strtolower (mysql_real_escape_string( $_POST['listNameInput'] ));
   $arr = explode('.',$_POST['selectlist'],2 );
   $nazwaListy = $arr[1];
   $id_listy = $arr[0];
   $checked = $_POST['checkbox'];

   if ( empty($checked))
   {//nie zaznaczono zadnego checkboxa
      echo '<br>Aby dodac punkty do listy zaznacz pole obok wybranych punktów';
      return;
   }
   if ($id_listy == -1)
   {
      echo 'Nie wybrales listy';
      return;
   }
   else if ($id_listy == 0 && $nowaNazwa== '')
   {
      echo 'Nie podałes nazwy listy';
      return;
   }
   global $database;
   $user = $_SESSION['ID'];
   $lastID = 0;
   if ($id_listy == 0 )
   {
      $select = "SELECT count(ID) as replay FROM lists WHERE ID_USER = '$user' AND name = '$nowaNazwa'";
      $database->query($select);
      $r=$database->getResult();
      if($r['replay'] > 0)
      {
         echo 'Posiadasz już listę o nazwie ' .$nowaNazwa ;
         return;
      }
      //make fisrt insert to lists table AKA create new list
      $insert = "INSERT INTO lists SET name = '$nowaNazwa', ID_USER='$user'";
      $database->query($insert);
      if (!$database->getReturn())
      {//gdy insert zwrócił false
         echo '<br>Nie udało się dodać listy ' .$nowaNazwa .' do bazy danych';
         return;
      }
      $lastID = mysql_insert_id();
      echo $lastID;
   }
   if($id_listy >0)
   {
      $nowaNazwa = $nazwaListy;
      $lastID = $id_listy;
   }

   $added = 0; //licznik dodanych punktow

   foreach($checked as $val)  //dla kazdego zaznaczonego punktu
   {
      //spr czy istnieje na wybranej liscie
      $select = "SELECT count(ID) as replay FROM `list-poi` WHERE ID_LIST = '$lastID' AND ID_POINT='$val'";
      $database->query($select);
      $r=$database->getResult();
      if($r['replay'] > 0)
      {//istnieje juz na liscie
         $select2 ="SELECT name FROM points WHERE ID = '$val'";
         $database->query($select2);
         $r=$database->getResult();
         if ($r['name'])
         {
            echo '<br>Na liście znajduje się już punkt o nazwie ' .$r['name'];
         }
      }
      else
      {//dodanie do listy
         $insert = "INSERT INTO `list-poi` SET ID_LIST = '$lastID', ID_POINT='$val'";
         $database->query($insert);
         $added++;
      }
   }
   if ($added >0)
   {
      echo '<BR>Pomyślnie dodano '.$added.' punkty/ów do listy '.$nowaNazwa .'.';
   }
   else
      echo '<br>Do listy '.$nowaNazwa.' nie dodano żadnych punktów.';

   if(isset($_POST['deltoo']))
      {//gdy user wybral usuniecie rowniez
         $this->delPointsFromList($checked,$_POST['list_id'] );
      }
}
function deleteList()
{
   global $database;
   $name =  $_GET['name'];
   $idListy = $_GET['id'];
   //  $_SESSION['ID']
   if ($this->listExists($name, $idListy, $_SESSION['ID']))
   {
      $delete = "DELETE FROM `list-poi` WHERE ID_LIST =".$idListy;
      $database->query($delete);
      $delete = "DELETE FROM lists WHERE ID = '$idListy' AND name = '$name' AND ID_USER = ".$_SESSION['ID'];
      $database->query($delete);
      echo "Lista '$name' została usunięta.";
   }
   else
   {
      echo 'Nie posiadasz listy o nazwie ' .$name .' lub próbujesz usunąć nie swoją listę.';
      return;
   }
}
   
function generateTrack()
{
   //unused
}
   
   /*
    * @return true if list with $name and $idListy (and created by user with $idUser) exists
    * otherwise returns false
    */
   function listExists($name, $idListy, $idUser =null)
   {
      global $database;
      if ( empty($name) || empty($idListy))
      {
         return false;
      }
      if ($idUser)
      {
         $select = "SELECT count(ID) as replay FROM lists WHERE ID = '$idListy' AND name = '$name' AND ID_USER = ".$idUser;
      }
      else
      {
         $select = "SELECT count(ID) as replay FROM lists WHERE ID = '$idListy' AND name = '$name'";
      }
      $database->query($select);
      $r=$database->getResult();
      if($r['replay'] == 0)
      {
         return false;
      }     
      return true;
   }

   function showPointsOnList($view)
   {
      global $database;
      $name =  $_GET['name'];
      $idListy = $_GET['id'];
      if ($this->listExists($name, $idListy, $_SESSION['ID']))
      {
         $select = "SELECT points.id, points.name, points.desc , points.lat, points.lon ,
   cat.name AS cname FROM (points LEFT JOIN cat ON points.id_cat = cat.id ) LEFT JOIN `list-poi` on points.id = `list-poi`.ID_POINT
WHERE `list-poi`.ID_LIST = ".$idListy;
         $database->query($select);

         if (mysql_num_rows($database->result) <=0)
         {
            echo ' Brak punktów na liście ' .$name .'.<br>';
            return;
         }
         ////są jakies punkty na liscie
         switch($view)
         {
            default:
            case 'general':
               echo ' Punkty na liście ' .$name .': <br> ';
               include('ShowAllPointsOnList.php');
               break;
            case 'track':
               echo ' Generowanie trasy z listy '.$name .' <br> ';
               include('pointsTrackGen.php');
               break;
         }       
      }
      else
      {
         echo 'Nie posiadasz listy o nazwie ' .$name .' lub próbujesz obejrzeć nie swoją listę.';
         return;
      }
   }


	function indexAction($db)
	{
      $this->database = $db;
      global $action;
         switch( $action)
         {
            case 'formAddPoints':
               include('formAddPoints.php');
               break;
           case 'formAddCat':
                  include('formAddCat.php');
                  break;
           case 'formAddFile':
                  include('formAddFile.php');
                  break;
            case 'formSearch':
               include('formSearch.php');
                  break;
           case 'addPoints':
                $this->addPoints();
                echo 'Poprawnie dodano punkt.';
               break;
            case 'addFile':
                  $this->addFile();
                  break;
            case 'addUCat':
                  include('showUcat.php');
                  $this->addUCat();
                  echo 'Dodano kategorię.';
                  break;
            case 'addCat':
               $this->addCat();
               echo 'Dodano kategorię.';
               break;
            case 'logout';
               break;
            case 'search':
               include('formSearch.php');
               include('showSearchResult.php');
               break;
            case 'delList':
               $this->deleteList();
               include('showAllLists.php');
               break;
            case 'xml':
            case 'export':
                if(isset($_POST['kml']))
                {
                    $this->exportKml();
                }
                if(isset($_POST['gpx']))
                {
                    $this->exportGpx();
                }
                if(isset($_POST['addToList']))
                {
                    $this->addToList();
                }
                if(isset($_POST['xslt']))
                {
                    $this->kmlXslt();
                }
                break;
             case 'exportFromList':
                if(isset($_POST['kml']))
                {
                    $this->exportKml();
                }
                if(isset($_POST['gpx']))
                {
                    $this->exportGpx();
                }
                if(isset($_POST['del']))
                {
                   $checked = $_POST['checkbox'];
                   $list_id = $_POST['list_id'];
                    $this->delPointsFromList($checked,$list_id );
                }
                if(isset($_POST['addToList']))
                {
                    $this->addToListFromExisting();
                }
                break;
            case 'showAllLists':
               include('showAllLists.php');
               break;
            case 'showList':
               $this->showPointsOnList('general');
               break;
             case 'xsl':
               include('formXSL.php');
                break;
            case 'gpx':
               $this->exportGpx();
               break;
             case 'gmaps':
                $this->Gmaps();
               break;
            case 'gmaps2':
               include('gmaps_test2.php');
               break;
            case 'gmaps3':
               include('gmaps_test3.php');
               break;
            case 'gmaps4':
               include('gmaps_test5.php');
               break;
            case 'gmaps5':
               include('gmaps_test6.php');
               break;
            case 'generateTrackFromList':
               $this->showPointsOnList('track');
               break;
            default :
               include('showAllPoints.php');
               break;
         }
	}
    //put your code here
}
?>
